#property copyright "Copyright 2024"
#property link      ""
#property version   "1.00"
#property strict

// 引入必要的库
#include <Trade/Trade.mqh>
#include <Trade/PositionInfo.mqh>

// 输入参数
input int      BollingerPeriod = 20;        // 布林带周期
input double   BollingerDeviation = 2.0;     // 布林带标准差
input int      ADXPeriod = 14;              // ADX周期
input int      ADXThreshold = 25;            // ADX阈值
input int      TrackCheckPeriod = 5;         // 检查延轨的K线数量
input int      TrackThreshold = 3;           // 延轨判断阈值
input double   FixedLot = 0.1;              // 固定手数
input int      MaxOrders = 3;               // 最大订单数量
input double   ATRPeriod = 14;              // ATR周期
input double   HedgeATRMultiplier = 3.0;    // 对冲ATR倍数

// 止盈参数
input group "止盈设置"
input bool     UsePartialTP = true;         // 启用分批止盈
input double   TP1Lot = 0.1;                // 第一单止盈手数
input double   TP2Lot = 0.1;                // 第二单止盈手数
input double   TP3Lot = 0.1;                // 第三单止盈手数
input int      ResistancePeriod = 66;       // 阻力位周期
input int      ResistanceShift = 8;         // 阻力位偏移
input bool     UseFullTP = true;            // 启用整体止盈

// 加仓参数
input group "加仓设置"
input int      PositionSpacing = 500;        // 加仓间距(点)
input bool     UsePositionSpacing = true;    // 启用加仓间距

// 全局变量
CTrade trade;                               // 交易对象
CPositionInfo positionInfo;                 // 持仓信息对象
int bollingerHandle;                        // 布林带指标句柄
int adxHandle;                              // ADX指标句柄
int atrHandle;                              // ATR指标句柄

// 状态变量
bool isTrackingUpper = false;               // 是否沿上轨运行
bool isTrackingLower = false;               // 是否沿下轨运行
double lastBuyPrice = 0;                    // 最后一次买入价
double lastSellPrice = 0;                   // 最后一次卖出价
int trackingCount = 0;                      // 延轨计数
int totalCount = 0;                         // 总计数

// 止盈状态结构
struct TP_State
{
    bool isTP1Executed;      // 第一单止盈是否执行
    bool isTP2Executed;      // 第二单止盈是否执行
    bool isTP3Executed;      // 第三单止盈是否执行
    double lastTPPrice;      // 上次止盈价格
    datetime lastTPTime;     // 上次止盈时间
    bool wasTracking;        // 是否曾经进入过延轨状态
    datetime trackingStartTime; // 进入延轨状态的时间
};

// 全局变量
TP_State buyTPState;    // 买单止盈状态
TP_State sellTPState;   // 卖单止盈状态

// 修改魔术号定义
#define NORMAL_MAGIC 123456
#define HEDGE_MAGIC 654321

// 全局变量
double lastBuyOpenPrice = 0;                 // 最后一次买入开仓价
double lastSellOpenPrice = 0;                // 最后一次卖出开仓价

// 函数声明
void OnInit();
void OnDeinit(const int reason);
void OnTick();
bool CheckTrackingStatus();
void CheckAndOpenOrders();
void CheckAndHedge();
void CheckTakeProfit();
void UpdateLabels();

//+------------------------------------------------------------------+
//| Expert initialization function                                     |
//+------------------------------------------------------------------+
void OnInit()
{
    // 初始化指标句柄
    bollingerHandle = iBands(_Symbol, PERIOD_CURRENT, BollingerPeriod, 0, BollingerDeviation, PRICE_CLOSE);
    adxHandle = iADX(_Symbol, PERIOD_CURRENT, ADXPeriod);
    atrHandle = iATR(_Symbol, PERIOD_CURRENT, ATRPeriod);
    
    if(bollingerHandle == INVALID_HANDLE || adxHandle == INVALID_HANDLE || atrHandle == INVALID_HANDLE)
    {
        Print("指标初始化失败!");
        ExpertRemove();
        return;
    }
    
    // 初始化交易设置
    trade.SetExpertMagicNumber(NORMAL_MAGIC);
    trade.SetMarginMode();
    trade.SetTypeFillingBySymbol(_Symbol);
    trade.SetDeviationInPoints(10);
    
    // 创建标签
    CreateLabels();
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                   |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    // 释放指标句柄
    IndicatorRelease(bollingerHandle);
    IndicatorRelease(adxHandle);
    IndicatorRelease(atrHandle);
    
    // 删除标签
    ObjectsDeleteAll(0, "BollingHedging_");
}

//+------------------------------------------------------------------+
//| Expert tick function                                              |
//+------------------------------------------------------------------+
void OnTick()
{
    // 检查新K线
    static datetime lastBarTime = 0;
    datetime currentBarTime = iTime(_Symbol, PERIOD_CURRENT, 0);
    
    // 只在新的K线形成时更新延轨状态
    if(lastBarTime != currentBarTime)
    {
        lastBarTime = currentBarTime;
        CheckTrackingStatus();
    }
    
    // 其他交易逻辑在每次tick时执行
    CheckAndOpenOrders();
    CheckAndHedge();
    CheckTakeProfit();
    UpdateLabels();
}

//+------------------------------------------------------------------+
//| 创建标签                                                           |
//+------------------------------------------------------------------+
void CreateLabels()
{
    // 创建状态标签
    ObjectCreate(0, "BollingHedging_Status", OBJ_LABEL, 0, 0, 0);
    ObjectSetInteger(0, "BollingHedging_Status", OBJPROP_CORNER, CORNER_LEFT_UPPER);
    ObjectSetInteger(0, "BollingHedging_Status", OBJPROP_XDISTANCE, 10);
    ObjectSetInteger(0, "BollingHedging_Status", OBJPROP_YDISTANCE, 20);
    ObjectSetString(0, "BollingHedging_Status", OBJPROP_TEXT, "状态: 初始化");
    
    // 创建价格标签
    ObjectCreate(0, "BollingHedging_LastBuy", OBJ_LABEL, 0, 0, 0);
    ObjectSetInteger(0, "BollingHedging_LastBuy", OBJPROP_CORNER, CORNER_LEFT_UPPER);
    ObjectSetInteger(0, "BollingHedging_LastBuy", OBJPROP_XDISTANCE, 10);
    ObjectSetInteger(0, "BollingHedging_LastBuy", OBJPROP_YDISTANCE, 40);
    ObjectSetString(0, "BollingHedging_LastBuy", OBJPROP_TEXT, "最后买入价: 0");
    
    ObjectCreate(0, "BollingHedging_LastSell", OBJ_LABEL, 0, 0, 0);
    ObjectSetInteger(0, "BollingHedging_LastSell", OBJPROP_CORNER, CORNER_LEFT_UPPER);
    ObjectSetInteger(0, "BollingHedging_LastSell", OBJPROP_XDISTANCE, 10);
    ObjectSetInteger(0, "BollingHedging_LastSell", OBJPROP_YDISTANCE, 60);
    ObjectSetString(0, "BollingHedging_LastSell", OBJPROP_TEXT, "最后卖出价: 0");
    
    // 创建止盈状态标签
    ObjectCreate(0, "BollingHedging_BuyTP", OBJ_LABEL, 0, 0, 0);
    ObjectSetInteger(0, "BollingHedging_BuyTP", OBJPROP_CORNER, CORNER_LEFT_UPPER);
    ObjectSetInteger(0, "BollingHedging_BuyTP", OBJPROP_XDISTANCE, 10);
    ObjectSetInteger(0, "BollingHedging_BuyTP", OBJPROP_YDISTANCE, 80);
    ObjectSetString(0, "BollingHedging_BuyTP", OBJPROP_TEXT, "买单止盈: 0 0 0");
    
    ObjectCreate(0, "BollingHedging_SellTP", OBJ_LABEL, 0, 0, 0);
    ObjectSetInteger(0, "BollingHedging_SellTP", OBJPROP_CORNER, CORNER_LEFT_UPPER);
    ObjectSetInteger(0, "BollingHedging_SellTP", OBJPROP_XDISTANCE, 10);
    ObjectSetInteger(0, "BollingHedging_SellTP", OBJPROP_YDISTANCE, 100);
    ObjectSetString(0, "BollingHedging_SellTP", OBJPROP_TEXT, "卖单止盈: 0 0 0");
    
    // 创建加仓信息标签
    ObjectCreate(0, "BollingHedging_BuySpacing", OBJ_LABEL, 0, 0, 0);
    ObjectSetInteger(0, "BollingHedging_BuySpacing", OBJPROP_CORNER, CORNER_LEFT_UPPER);
    ObjectSetInteger(0, "BollingHedging_BuySpacing", OBJPROP_XDISTANCE, 10);
    ObjectSetInteger(0, "BollingHedging_BuySpacing", OBJPROP_YDISTANCE, 120);
    ObjectSetString(0, "BollingHedging_BuySpacing", OBJPROP_TEXT, "买入加仓价: 0");
    
    ObjectCreate(0, "BollingHedging_SellSpacing", OBJ_LABEL, 0, 0, 0);
    ObjectSetInteger(0, "BollingHedging_SellSpacing", OBJPROP_CORNER, CORNER_LEFT_UPPER);
    ObjectSetInteger(0, "BollingHedging_SellSpacing", OBJPROP_XDISTANCE, 10);
    ObjectSetInteger(0, "BollingHedging_SellSpacing", OBJPROP_YDISTANCE, 140);
    ObjectSetString(0, "BollingHedging_SellSpacing", OBJPROP_TEXT, "卖出加仓价: 0");
}

//+------------------------------------------------------------------+
//| 更新标签                                                           |
//+------------------------------------------------------------------+
void UpdateLabels()
{
    string status = "正常";
    if(isTrackingUpper) status = "沿上轨";
    if(isTrackingLower) status = "沿下轨";
    
    ObjectSetString(0, "BollingHedging_Status", OBJPROP_TEXT, "状态: " + status);
    ObjectSetString(0, "BollingHedging_LastBuy", OBJPROP_TEXT, "最后买入价: " + DoubleToString(lastBuyPrice, _Digits));
    ObjectSetString(0, "BollingHedging_LastSell", OBJPROP_TEXT, "最后卖出价: " + DoubleToString(lastSellPrice, _Digits));
    
    // 添加止盈状态显示
    string buyTPStatus = "买单止盈: " + 
                        (buyTPState.isTP1Executed ? "1" : "0") + " " +
                        (buyTPState.isTP2Executed ? "1" : "0") + " " +
                        (buyTPState.isTP3Executed ? "1" : "0");
    string sellTPStatus = "卖单止盈: " + 
                         (sellTPState.isTP1Executed ? "1" : "0") + " " +
                         (sellTPState.isTP2Executed ? "1" : "0") + " " +
                         (sellTPState.isTP3Executed ? "1" : "0");
    
    ObjectSetString(0, "BollingHedging_BuyTP", OBJPROP_TEXT, buyTPStatus);
    ObjectSetString(0, "BollingHedging_SellTP", OBJPROP_TEXT, sellTPStatus);
    
    // 添加加仓信息显示
    string buySpacing = "买入加仓价: " + DoubleToString(lastBuyOpenPrice, _Digits);
    string sellSpacing = "卖出加仓价: " + DoubleToString(lastSellOpenPrice, _Digits);
    
    ObjectSetString(0, "BollingHedging_BuySpacing", OBJPROP_TEXT, buySpacing);
    ObjectSetString(0, "BollingHedging_SellSpacing", OBJPROP_TEXT, sellSpacing);
}

//+------------------------------------------------------------------+
//| 检查延轨状态                                                         |
//+------------------------------------------------------------------+
bool CheckTrackingStatus()
{
    double upperBand[], lowerBand[], high[], low[];
    ArraySetAsSeries(upperBand, true);
    ArraySetAsSeries(lowerBand, true);
    ArraySetAsSeries(high, true);
    ArraySetAsSeries(low, true);
    
    // 获取布林带数据
    if(CopyBuffer(bollingerHandle, 1, 0, TrackCheckPeriod, upperBand) <= 0 ||
       CopyBuffer(bollingerHandle, 2, 0, TrackCheckPeriod, lowerBand) <= 0 ||
       CopyHigh(_Symbol, PERIOD_CURRENT, 0, TrackCheckPeriod, high) <= 0 ||
       CopyLow(_Symbol, PERIOD_CURRENT, 0, TrackCheckPeriod, low) <= 0)
    {
        Print("获取指标数据失败!");
        return false;
    }
    
    // 检查上轨延轨
    int upperTrackCount = 0;
    for(int i = 0; i < TrackCheckPeriod; i++)
    {
        // 检查K线（包括影线）是否穿过上轨
        if(high[i] >= upperBand[i])
            upperTrackCount++;
    }
    
    // 检查下轨延轨
    int lowerTrackCount = 0;
    for(int i = 0; i < TrackCheckPeriod; i++)
    {
        // 检查K线（包括影线）是否穿过下轨
        if(low[i] <= lowerBand[i])
            lowerTrackCount++;
    }
    
    // 更新延轨状态
    isTrackingUpper = (upperTrackCount >= TrackThreshold);
    isTrackingLower = (lowerTrackCount >= TrackThreshold);
    
    // 更新计数
    if(isTrackingUpper || isTrackingLower)
        trackingCount++;
    totalCount++;
    
    Print("延轨状态更新 - 上轨: ", isTrackingUpper ? "是" : "否", 
          " 下轨: ", isTrackingLower ? "是" : "否",
          " 上轨计数: ", upperTrackCount,
          " 下轨计数: ", lowerTrackCount);
    
    return true;
}

//+------------------------------------------------------------------+
//| 获取当前订单数量                                                     |
//+------------------------------------------------------------------+
int GetCurrentOrdersCount(ENUM_POSITION_TYPE type, int magic = NORMAL_MAGIC)
{
    int count = 0;
    for(int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if(positionInfo.SelectByIndex(i))
        {
            if(positionInfo.Symbol() == _Symbol && 
               positionInfo.PositionType() == type &&
               positionInfo.Magic() == magic)
                count++;
        }
    }
    return count;
}

//+------------------------------------------------------------------+
//| 检查并开仓                                                          |
//+------------------------------------------------------------------+
void CheckAndOpenOrders()
{
    double upperBand[], lowerBand[], open[];
    ArraySetAsSeries(upperBand, true);
    ArraySetAsSeries(lowerBand, true);
    ArraySetAsSeries(open, true);
    
    // 获取指标数据
    if(CopyBuffer(bollingerHandle, 1, 0, 1, upperBand) <= 0 ||
       CopyBuffer(bollingerHandle, 2, 0, 1, lowerBand) <= 0 ||
       CopyOpen(_Symbol, PERIOD_CURRENT, 0, 1, open) <= 0)
    {
        Print("获取指标数据失败!");
        return;
    }
    
    double currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
    // 检查买入条件
    int buyCount = GetCurrentOrdersCount(POSITION_TYPE_BUY);
    // 检查当前价格是否满足开仓条件
    if(currentPrice > lowerBand[0] && open[0] < lowerBand[0])
    {
        // 检查是否在延轨状态
        if(!isTrackingUpper || buyCount == 0)
        {
            // 检查加仓间距
            bool canOpen = true;
            if(UsePositionSpacing && buyCount > 0)
            {
                double spacing = MathAbs(currentPrice - lastBuyOpenPrice) / _Point;
                if(spacing < PositionSpacing)
                {
                    Print("买入加仓间距不足，当前间距: ", spacing, " 点，需要: ", PositionSpacing, " 点");
                    canOpen = false;
                }
            }
            
            // 平掉对冲单
            CloseHedgePositions(POSITION_TYPE_SELL);
            
            // 更新价格记录
            lastBuyPrice = currentPrice;
            lastBuyOpenPrice = currentPrice;
            
            // 只有在未达到最大单量时才开仓
            if(canOpen && buyCount < MaxOrders)
            {
                // 开买单
                if(trade.Buy(FixedLot, _Symbol, 0, 0, 0, "Bollinger Buy"))
                {
                    Print("开买单成功，价格: ", lastBuyPrice, " 订单数: ", buyCount + 1);
                }
            }
            else if(buyCount >= MaxOrders)
            {
                Print("达到最大买单数量，仅更新价格记录: ", lastBuyPrice);
            }
        }
    }
    
    // 检查卖出条件
    int sellCount = GetCurrentOrdersCount(POSITION_TYPE_SELL);
    // 检查当前价格是否满足开仓条件
    if(currentPrice < upperBand[0] && open[0] > upperBand[0])
    {
        // 检查是否在延轨状态
        if(!isTrackingLower || sellCount == 0)
        {
            // 检查加仓间距
            bool canOpen = true;
            if(UsePositionSpacing && sellCount > 0)
            {
                double spacing = MathAbs(currentPrice - lastSellOpenPrice) / _Point;
                if(spacing < PositionSpacing)
                {
                    Print("卖出加仓间距不足，当前间距: ", spacing, " 点，需要: ", PositionSpacing, " 点");
                    canOpen = false;
                }
            }
            
            // 平掉对冲单
            CloseHedgePositions(POSITION_TYPE_BUY);
            
            // 更新价格记录
            lastSellPrice = currentPrice;
            lastSellOpenPrice = currentPrice;
            
            // 只有在未达到最大单量时才开仓
            if(canOpen && sellCount < MaxOrders)
            {
                // 开卖单
                if(trade.Sell(FixedLot, _Symbol, 0, 0, 0, "Bollinger Sell"))
                {
                    Print("开卖单成功，价格: ", lastSellPrice, " 订单数: ", sellCount + 1);
                }
            }
            else if(sellCount >= MaxOrders)
            {
                Print("达到最大卖单数量，仅更新价格记录: ", lastSellPrice);
            }
        }
    }
}

//+------------------------------------------------------------------+
//| 检查并执行对冲                                                      |
//+------------------------------------------------------------------+
void CheckAndHedge()
{
    double atr[];
    ArraySetAsSeries(atr, true);
    
    if(CopyBuffer(atrHandle, 0, 0, 1, atr) <= 0)
    {
        Print("获取ATR数据失败!");
        return;
    }
    
    double currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
    // 检查买入单是否需要对冲
    if(lastBuyPrice > 0 && currentPrice < lastBuyPrice - HedgeATRMultiplier * atr[0])
    {
        int buyCount = GetCurrentOrdersCount(POSITION_TYPE_BUY);
        int sellCount = GetCurrentOrdersCount(POSITION_TYPE_SELL, HEDGE_MAGIC);
        
        if(buyCount > sellCount)
        {
            double hedgeLot = (buyCount - sellCount) * FixedLot;
            // 临时修改魔术号
            trade.SetExpertMagicNumber(HEDGE_MAGIC);
            if(trade.Sell(hedgeLot, _Symbol, 0, 0, 0, "Hedge Sell"))
            {
                Print("执行对冲卖单，手数: ", hedgeLot);
            }
            // 恢复魔术号
            trade.SetExpertMagicNumber(NORMAL_MAGIC);
        }
    }
    
    // 检查卖出单是否需要对冲
    if(lastSellPrice > 0 && currentPrice > lastSellPrice + HedgeATRMultiplier * atr[0])
    {
        int buyCount = GetCurrentOrdersCount(POSITION_TYPE_BUY, HEDGE_MAGIC);
        int sellCount = GetCurrentOrdersCount(POSITION_TYPE_SELL);
        
        if(sellCount > buyCount)
        {
            double hedgeLot = (sellCount - buyCount) * FixedLot;
            // 临时修改魔术号
            trade.SetExpertMagicNumber(HEDGE_MAGIC);
            if(trade.Buy(hedgeLot, _Symbol, 0, 0, 0, "Hedge Buy"))
            {
                Print("执行对冲买单，手数: ", hedgeLot);
            }
            // 恢复魔术号
            trade.SetExpertMagicNumber(NORMAL_MAGIC);
        }
    }
}

//+------------------------------------------------------------------+
//| 检查并执行止盈                                                      |
//+------------------------------------------------------------------+
void CheckTakeProfit()
{
    if(!UsePartialTP) return;
    
    // 检查买单止盈
    CheckBuyTakeProfit();
    
    // 检查卖单止盈
    CheckSellTakeProfit();
}

//+------------------------------------------------------------------+
//| 检查买单止盈                                                        |
//+------------------------------------------------------------------+
void CheckBuyTakeProfit()
{
    int buyCount = GetCurrentOrdersCount(POSITION_TYPE_BUY);
    if(buyCount == 0) return;
    
    double upperBand[], middleBand[];
    ArraySetAsSeries(upperBand, true);
    ArraySetAsSeries(middleBand, true);
    
    if(CopyBuffer(bollingerHandle, 1, 0, 1, upperBand) <= 0 ||
       CopyBuffer(bollingerHandle, 0, 0, 1, middleBand) <= 0)
        return;
        
    double currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    
    // 更新延轨状态记录
    if(isTrackingUpper && !buyTPState.wasTracking)
    {
        buyTPState.wasTracking = true;
        buyTPState.trackingStartTime = TimeCurrent();
        Print("买单进入延轨状态，时间: ", TimeToString(buyTPState.trackingStartTime));
    }
    
    // 第一单止盈：价格触及布林带上轨
    if(!buyTPState.isTP1Executed && currentPrice >= upperBand[0])
    {
        double lotToClose = MathMin(TP1Lot, GetPositionLots(POSITION_TYPE_BUY));
        if(ClosePartialPosition(POSITION_TYPE_BUY, lotToClose, "TP1 - Upper Band"))
        {
            buyTPState.isTP1Executed = true;
            buyTPState.lastTPPrice = currentPrice;
            buyTPState.lastTPTime = TimeCurrent();
            Print("买单第一单止盈执行，价格: ", currentPrice, " 手数: ", lotToClose);
        }
    }
    
    // 第二单止盈：延轨状态结束（必须曾经进入过延轨状态）
    if(!buyTPState.isTP2Executed && buyTPState.wasTracking && !isTrackingUpper)
    {
        double lotToClose = MathMin(TP2Lot, GetPositionLots(POSITION_TYPE_BUY));
        if(ClosePartialPosition(POSITION_TYPE_BUY, lotToClose, "TP2 - Tracking End"))
        {
            buyTPState.isTP2Executed = true;
            buyTPState.lastTPPrice = currentPrice;
            buyTPState.lastTPTime = TimeCurrent();
            Print("买单第二单止盈执行，价格: ", currentPrice, " 手数: ", lotToClose);
        }
    }
    
    // 第三单止盈：阻力位
    if(!buyTPState.isTP3Executed && IsResistanceLevel(currentPrice, true))
    {
        double lotToClose = MathMin(TP3Lot, GetPositionLots(POSITION_TYPE_BUY));
        if(ClosePartialPosition(POSITION_TYPE_BUY, lotToClose, "TP3 - Resistance"))
        {
            buyTPState.isTP3Executed = true;
            buyTPState.lastTPPrice = currentPrice;
            buyTPState.lastTPTime = TimeCurrent();
            Print("买单第三单止盈执行，价格: ", currentPrice, " 手数: ", lotToClose);
        }
    }
    
    // 整体止盈条件
    if(UseFullTP && !buyTPState.isTP1Executed && !buyTPState.isTP2Executed)
    {
        // 如果价格到达阻力位，且没有执行过第一单和第二单止盈，则平掉所有
        if(IsResistanceLevel(currentPrice, true))
        {
            CloseAllPositions(POSITION_TYPE_BUY, "Full TP - Resistance");
            Print("买单整体止盈执行，价格: ", currentPrice);
        }
    }
}

//+------------------------------------------------------------------+
//| 检查卖单止盈                                                        |
//+------------------------------------------------------------------+
void CheckSellTakeProfit()
{
    int sellCount = GetCurrentOrdersCount(POSITION_TYPE_SELL);
    if(sellCount == 0) return;
    
    double lowerBand[], middleBand[];
    ArraySetAsSeries(lowerBand, true);
    ArraySetAsSeries(middleBand, true);
    
    if(CopyBuffer(bollingerHandle, 2, 0, 1, lowerBand) <= 0 ||
       CopyBuffer(bollingerHandle, 0, 0, 1, middleBand) <= 0)
        return;
        
    double currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    
    // 更新延轨状态记录
    if(isTrackingLower && !sellTPState.wasTracking)
    {
        sellTPState.wasTracking = true;
        sellTPState.trackingStartTime = TimeCurrent();
        Print("卖单进入延轨状态，时间: ", TimeToString(sellTPState.trackingStartTime));
    }
    
    // 第一单止盈：价格触及布林带下轨
    if(!sellTPState.isTP1Executed && currentPrice <= lowerBand[0])
    {
        double lotToClose = MathMin(TP1Lot, GetPositionLots(POSITION_TYPE_SELL));
        if(ClosePartialPosition(POSITION_TYPE_SELL, lotToClose, "TP1 - Lower Band"))
        {
            sellTPState.isTP1Executed = true;
            sellTPState.lastTPPrice = currentPrice;
            sellTPState.lastTPTime = TimeCurrent();
            Print("卖单第一单止盈执行，价格: ", currentPrice, " 手数: ", lotToClose);
        }
    }
    
    // 第二单止盈：延轨状态结束（必须曾经进入过延轨状态）
    if(!sellTPState.isTP2Executed && sellTPState.wasTracking && !isTrackingLower)
    {
        double lotToClose = MathMin(TP2Lot, GetPositionLots(POSITION_TYPE_SELL));
        if(ClosePartialPosition(POSITION_TYPE_SELL, lotToClose, "TP2 - Tracking End"))
        {
            sellTPState.isTP2Executed = true;
            sellTPState.lastTPPrice = currentPrice;
            sellTPState.lastTPTime = TimeCurrent();
            Print("卖单第二单止盈执行，价格: ", currentPrice, " 手数: ", lotToClose);
        }
    }
    
    // 第三单止盈：支撑位
    if(!sellTPState.isTP3Executed && IsResistanceLevel(currentPrice, false))
    {
        double lotToClose = MathMin(TP3Lot, GetPositionLots(POSITION_TYPE_SELL));
        if(ClosePartialPosition(POSITION_TYPE_SELL, lotToClose, "TP3 - Support"))
        {
            sellTPState.isTP3Executed = true;
            sellTPState.lastTPPrice = currentPrice;
            sellTPState.lastTPTime = TimeCurrent();
            Print("卖单第三单止盈执行，价格: ", currentPrice, " 手数: ", lotToClose);
        }
    }
    
    // 整体止盈条件
    if(UseFullTP && !sellTPState.isTP1Executed && !sellTPState.isTP2Executed)
    {
        // 如果价格到达支撑位，且没有执行过第一单和第二单止盈，则平掉所有
        if(IsResistanceLevel(currentPrice, false))
        {
            CloseAllPositions(POSITION_TYPE_SELL, "Full TP - Support");
            Print("卖单整体止盈执行，价格: ", currentPrice);
        }
    }
}

//+------------------------------------------------------------------+
//| 检查是否为阻力/支撑位                                               |
//+------------------------------------------------------------------+
bool IsResistanceLevel(double price, bool isResistance)
{
    double high[], low[];
    ArraySetAsSeries(high, true);
    ArraySetAsSeries(low, true);
    
    if(CopyHigh(_Symbol, PERIOD_CURRENT, 0, ResistancePeriod, high) <= 0 ||
       CopyLow(_Symbol, PERIOD_CURRENT, 0, ResistancePeriod, low) <= 0)
        return false;
    
    if(isResistance)
    {
        // 检查是否为阻力位
        for(int i = ResistanceShift; i < ResistancePeriod - ResistanceShift; i++)
        {
            if(high[i] > high[i-1] && high[i] > high[i+1])
            {
                if(MathAbs(price - high[i]) < _Point * 10)
                    return true;
            }
        }
    }
    else
    {
        // 检查是否为支撑位
        for(int i = ResistanceShift; i < ResistancePeriod - ResistanceShift; i++)
        {
            if(low[i] < low[i-1] && low[i] < low[i+1])
            {
                if(MathAbs(price - low[i]) < _Point * 10)
                    return true;
            }
        }
    }
    
    return false;
}

//+------------------------------------------------------------------+
//| 部分平仓                                                           |
//+------------------------------------------------------------------+
bool ClosePartialPosition(ENUM_POSITION_TYPE type, double lot, string comment)
{
    for(int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if(positionInfo.SelectByIndex(i))
        {
            if(positionInfo.Symbol() == _Symbol && 
               positionInfo.PositionType() == type &&
               positionInfo.Magic() == NORMAL_MAGIC)
            {
                if(trade.PositionClosePartial(positionInfo.Ticket(), lot))
                {
                    Print("部分平仓成功，订单号: ", positionInfo.Ticket(), 
                          " 手数: ", lot, " 注释: ", comment);
                    return true;
                }
            }
        }
    }
    return false;
}

//+------------------------------------------------------------------+
//| 平掉所有对冲单                                                      |
//+------------------------------------------------------------------+
void CloseHedgePositions(ENUM_POSITION_TYPE type)
{
    for(int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if(positionInfo.SelectByIndex(i))
        {
            if(positionInfo.Symbol() == _Symbol && 
               positionInfo.PositionType() == type &&
               positionInfo.Magic() == HEDGE_MAGIC)
            {
                trade.PositionClose(positionInfo.Ticket());
                Print("平掉对冲单，订单号: ", positionInfo.Ticket());
            }
        }
    }
}

//+------------------------------------------------------------------+
//| 获取指定类型持仓的总手数                                            |
//+------------------------------------------------------------------+
double GetPositionLots(ENUM_POSITION_TYPE type)
{
    double totalLots = 0;
    for(int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if(positionInfo.SelectByIndex(i))
        {
            if(positionInfo.Symbol() == _Symbol && 
               positionInfo.PositionType() == type &&
               positionInfo.Magic() == NORMAL_MAGIC)
            {
                totalLots += positionInfo.Volume();
            }
        }
    }
    return totalLots;
}

//+------------------------------------------------------------------+
//| 平掉所有指定类型的持仓                                              |
//+------------------------------------------------------------------+
void CloseAllPositions(ENUM_POSITION_TYPE type, string comment)
{
    for(int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if(positionInfo.SelectByIndex(i))
        {
            if(positionInfo.Symbol() == _Symbol && 
               positionInfo.PositionType() == type &&
               positionInfo.Magic() == NORMAL_MAGIC)
            {
                if(trade.PositionClose(positionInfo.Ticket()))
                {
                    Print("平仓成功，订单号: ", positionInfo.Ticket(), " 注释: ", comment);
                }
            }
        }
    }
} 